'use strict';
const fs = require('fs');
const rimraf = require('rimraf');
const exec = require('child_process').exec;
const chalk = require('chalk');
const ora = require('ora');
const path = require('./path');

// 清空远程仓库
const claerWarehouse = () => new Promise((resolve, reject) => {
    rimraf(`${path.rootPath}${path.warehouse()}`, err => {
        if (err) throw err;
        resolve();
    });
});

// 检查更新
module.exports = callback => {
    return new Promise(res => {
        claerWarehouse().then(() => {
            const spinner = ora(' 正在检查更新...').start();
            // 下载更新远程仓库
            exec(`git clone -b ocj-cli git@10.22.218.111:FETools/CF.git ${path.rootPath}${path.warehouse()}`,
             (error, stdout, stderr) => {
                if(error) {
                    console.log(chalk.bgRed(stderr));
                    process.exit();
                } else {
                    // 下载成功
                    spinner.stop();
                    // 读取package.json
                    Promise.all([
                        new Promise((resolve, reject) => {
                            fs.readFile(`${path.rootPath}${path.warehouse()}/package.json`, 'utf-8', function(err, data){ 
                                if (err) reject(err);
                                resolve(JSON.parse(data));
                            });
                        }),
                        new Promise((resolve, reject) => {
                            fs.readFile(`${path.rootPath}/package.json`, 'utf-8', function(err, data){ 
                                if (err) reject(err);
                                resolve(JSON.parse(data));
                            });
                        })
                    ]).then(d => {
                        // 判断版本是否相同
                        if(d[1].version !== d[0].version) {
                            console.log(chalk.bgYellow(`发现有新版本可更新 ${ d[1].version } ==>　${ d[0].version }`));
                        } else {
                            console.log(chalk.green(`当前版本${ d[0].version }已是最新`));
                        }
                        res();
                    }).catch(err => {
                        throw err;
                    });
                }
            });
        });
    });
};